package com.singletonapps.evory.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.singletonapps.evory.dto.CourseDto;
import com.singletonapps.evory.dto.ResponseDto;
import com.singletonapps.evory.exception.CreateCourseException;
import com.singletonapps.evory.exception.GuardaArchivoServerException;
import com.singletonapps.evory.service.AdminService;

@Controller
@RequestMapping("/private/admin")
public class AdminController {
	
	private static final Logger LOGGER = LogManager.getLogger(AdminController.class.getName());
	
	@Autowired
	private AdminService adminService;
	
	@RequestMapping(value = "/init")
	public String adminInit(ModelMap map){
		
		map.put("cursos", adminService.cargaTodosLosCursos());
		
		return "admin/adminIndex";
	}
	
	@RequestMapping(value = "/crearCurso", method = RequestMethod.POST)
	public String crearCurso(@ModelAttribute("curso") CourseDto curso, @RequestParam("cursoImagen") MultipartFile imagen, 
			@RequestParam("materialFile") MultipartFile[] materiales, @RequestParam("videoFile") MultipartFile[] videos ,ModelMap map){
		
		ResponseDto respuesta = new ResponseDto();
		
		try {
			respuesta = adminService.createCourse(curso, imagen, materiales, videos);
		} catch (CreateCourseException | GuardaArchivoServerException e) {
			LOGGER.error(e.getMessage());
			respuesta.getErrors().add(e.getMessage());
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
			respuesta.getErrors().add("Se presento un problema creando el curso");
		}
		
		map.put("respuesta", respuesta);
		
		return "admin/adminIndex";
	}

}
